package demo.using.reg;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : GuoFei
 * @since : 2019/6/26 14:03
 */
public class DealFile {



    public static void main(String[] args) throws IOException {
        String dirPath = "D:\\test\\reg";
        List<String> list = showPathFiles(dirPath);
        list.forEach(DealFile::dealFile);
    }

    private static List<String> showPathFiles(String dirPath) {
        File file = new File(dirPath);
        List<String> list = new ArrayList<>();
        File[] files = file.listFiles();
        if (files == null) {
            return list;
        }
        for (File file1 : files) {
            list.add(file1.getPath());
        }
        return list;
    }


    public static void dealFiles(List<String> files) {
        for (String file : files) {
            dealFile(file);
        }
    }

    private static void dealFile(String filePath) {

        String res = null;
        try {
            res = IOUtils.toString(new FileInputStream(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (res == null) {
            return;
        }
        res = res.replaceAll("(<[\\s\\S]*?>)|(&nbsp;)|((?<=在线练习)([\\s\\S]*?)(?=练习科目))", "\n");
        res = res.replaceAll("(^\\n$)|(function (.*) \\{([\\s\\S]*)})|(^ +)", "");
        // 删除空行
        res=res.replaceAll("(?m)(?:\\n|\\r\\n)(?:^\\s*$)", "");
        res=res.replaceAll("(?m)(?:^\\s*$(?:\\n|\\r\\n))", "");

        System.out.println(res);

        String resFilePath = filePath.replaceAll(".txt", "_res.txt");

        try {
            fullFilePath(resFilePath);
            IOUtils.write(res,new FileOutputStream(resFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private static void fullFilePath(String filePath) throws IOException {
        filePath.replace("/", "\\");
        String path = filePath.substring(0,filePath.lastIndexOf("\\")+1);
        String name = filePath.substring(filePath.lastIndexOf("\\")+1);
        fullFilePath(path,name);
    }

    private static void fullFilePath(String dirPath, String fileName) throws IOException {
        File file = new File(dirPath,fileName);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
    }

}
